package zkk.com.mengqu.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.base.library.util.WDYLog;
import com.base.library.view.upPhotoView.DoPicCapUtil;
import com.base.library.view.upPhotoView.UpPhotoView;
import com.bumptech.glide.Glide;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import zkk.com.mengqu.R;
import zkk.com.mengqu.manager.APIManager;
import zkk.com.mengqu.models.Tietuku;
import zkk.com.mengqu.models.User;
import zkk.com.mengqu.models.UserInfo;
import zkk.com.mengqu.simplepreferences.Share;
import zkk.com.mengqu.util.FinalString;
import zkk.com.mengqu.util.GlideCircleTransform;

/**
 * Created by Administrator on 2017/6/15.
 */
public class UserDetailActivity extends Activity implements View.OnClickListener{
    private Context context;
    private ImageView back, userIcon;//返回，用户头像
    private TextView updateUser, submitUser, txUserName, txUserSex, txUserAddress;
    private Button logout;
    private EditText etUserName, etUserSex, etUserAddress;

    private UpPhotoView upPhotoView;
//    private String Path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail);
        initView();
        upPhotoView = new UpPhotoView(this);

        Log.w("UpPhotoView--", "UpPhotoView");
        upPhotoView.setOnPhotoLinear(new UpPhotoView.onPhotoLinear() {
            @Override
            public void selectPhoto(String path) {
                WDYLog.d("一般咨询", "本地路径" + path);
                Log.w("UpPhotoView--", "" + path);
//                Path = path;
                updateImage(path);
                userIcon.setImageBitmap(DoPicCapUtil.makeRoundCorner(DoPicCapUtil.getSmallBitmap(path)));

            }
        });
    }

    private void initView(){
        context = getApplicationContext();
        back = (ImageView)findViewById(R.id.iv_back);
        userIcon = (ImageView)findViewById(R.id.iv_user_icon);
        updateUser = (TextView)findViewById(R.id.tx_update_user);
        submitUser = (TextView)findViewById(R.id.tx_update_user_submit);
        txUserName = (TextView)findViewById(R.id.tx_user_name);
        txUserSex = (TextView)findViewById(R.id.tx_user_sex);
        txUserAddress = (TextView)findViewById(R.id.tx_user_address);
        logout = (Button)findViewById(R.id.btn_logout);
        etUserName = (EditText)findViewById(R.id.et_user_name);
        etUserSex = (EditText)findViewById(R.id.et_user_sex);
        etUserAddress = (EditText)findViewById(R.id.et_user_address);



        back.setOnClickListener(this);
        userIcon.setOnClickListener(this);
        updateUser.setOnClickListener(this);
        submitUser.setOnClickListener(this);
        logout.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //读取存储的数据
        load();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tx_update_user:
                showView(true);
                break;
            case R.id.tx_update_user_submit:
                updateUser();
                finish();
                break;
            case R.id.btn_logout:
                Share.logout();
                finish();
                break;
            case R.id.iv_user_icon:
                upPhotoView.showView();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        upPhotoView.ActivityResult(requestCode, resultCode, data);

    }

    public void load(){
        txUserName.setText(Share.getUserName());
        txUserSex.setText(Share.getUserSex());
        txUserAddress.setText(Share.getUserAddress());

        etUserName.setText(Share.getUserName());
        etUserSex.setText(Share.getUserSex());
        etUserAddress.setText(Share.getUserAddress());
        Glide.with(this)
                .load(Share.getIcon())
                .override(300,300)
                .placeholder(R.drawable.ic_user_icon_default)//加载中
                .error(R.drawable.ic_user_icon_default)//加载失败
                .transform(new GlideCircleTransform(context))//将图片变成圆形
                .into(userIcon);
    }

    public void showView(boolean type){
        updateUser.setVisibility(type ? View.GONE : View.VISIBLE);
        submitUser.setVisibility(type ? View.VISIBLE : View.GONE);

        etUserName.setVisibility(type ? View.VISIBLE : View.GONE);
        etUserSex.setVisibility(type ? View.VISIBLE : View.GONE);
        etUserAddress.setVisibility(type ? View.VISIBLE : View.GONE);

        txUserName.setVisibility(type ? View.GONE : View.VISIBLE);
        txUserSex.setVisibility(type ? View.GONE : View.VISIBLE);
        txUserAddress.setVisibility(type ? View.GONE : View.VISIBLE);

        logout.setVisibility(type ? View.GONE : View.VISIBLE);
    }

    /**
     * 修改用户信息
     */
    public void updateUser(){
        int id = Integer.parseInt(Share.getUserId());
        String name = etUserName.getText().toString().trim();
        int sex = Integer.parseInt(etUserSex.getText().toString().trim());
        String address = etUserAddress.getText().toString().trim();

        User user = new User(id, name, sex, address);

        APIManager.setManager()
                .updateUser(user)
                .enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        User rUser = response.body();
                        Log.e("onNext", ""+ rUser.getAddr());
                        Map<String,String> maps = new HashMap<>();
                        maps.put(Share.USERNAME,"" + rUser.getName());
                        maps.put(Share.UID,"" + rUser.getId());
                        maps.put(Share.SEX,"" + rUser.getSex());
                        maps.put(Share.ADDRESS,"" + rUser.getAddr());
                        Share.setShare(maps);
                        showView(false);
                        load();
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        t.printStackTrace();
                        Log.e("onError", "onError");
                    }
                });
    }

    /**
     * 将头像上传到服务器
     * @param path
     */
    public void updateImage(String path){
//        RequestBody requestFile =
//                RequestBody.create(MediaType.parse("multipart/form-data"), new File(path));
        File file = new File(path);
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("Token", FinalString.token)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                .build();

        APIManager.tieTUkuManager()
                .importImage(requestBody)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Tietuku>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Tietuku tietuku) {
                        Log.w("tietuku", "" + tietuku);
                        updateIcon(tietuku.getsUrl());
                    }
                });
    }

    /**
     * 修改用户头像地址
     * @param path
     */
    public void updateIcon(String path){
        int uid = Integer.parseInt(Share.getUserId());
        APIManager.setManager()
                .updateIcon(uid, path)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(User user) {
                        Map<String,String> maps = new HashMap<>();
                        maps.put(Share.USERNAME,""+user.getName());
                        maps.put(Share.UID,""+user.getId());
                        maps.put(Share.TOKEN,""+user.getToken());
                        maps.put(Share.SEX,""+user.getSex());
                        maps.put(Share.SEX,""+user.getSex());
                        maps.put(Share.PHONE,""+user.getPhone());
                        maps.put(Share.ICON,""+user.getHead_path());
                        Share.setShare(maps);
                        load();
                    }
                });

    }
}
